//
//  LoginWechatViewController.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/4/17.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class LoginWechatViewController: NSViewController {
    
    var timer:DispatchSourceTimer?
    let timeDefault:Int = 59
    var timeCount:Int = 59
    
    //时间戳微信参数
    var sinle:String?
    //图片大小
    let kqrx = CGFloat(220)
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kHomeWinWidth, kHomeWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
        self.loadData()
    }
    
    deinit {
        if self.timer != nil {
            self.timer?.cancel()
            self.timer = nil
        }
        self.timeCount = timeDefault
        
        self.sinle = nil
        
        NotificationCenter.default.removeObserver(self)
    }
    
    func loadData() {
        if self.timer != nil {
            self.timer?.cancel()
            self.timer = nil
        }
        self.timeCount = timeDefault
        
        self.setQrImageV(url: self.getsSinleUrl())
        self.reCheckLogin()
    }
    
    func getsSinleUrl() -> String {
        let curTime = String.init(format: "%.0f", Date.init().timeIntervalSince1970)
        let sin = Int.randomIntNumber(lower: 1000, upper: 9999)
        let sinle = String.init(format: "%@%d", curTime,sin)
        let url = "https://www.1meeting.cn/mobile/pcwechat/"+sinle
        self.sinle = sinle
        return url
    }
    
    func setQrImageV(url:String)  {
        self.qrImageV.image = QRManager.createQRImage(message: url, size: NSSize.init(width: kqrx, height: kqrx), backgroundColor: .white, foregroundColor: .black, fillImage: nil)
    }
    
    func reCheckLogin() {
        
        self.qrInvalid.isHidden = true
       
        guard let sin = self.sinle else {
            self.setQrImageV(url: self.getsSinleUrl())
            self.reCheckLogin()
            return
        }
        
        
        self.timer = self.dispatchTimer(timeInterval: 1, repeatCount: timeDefault) { (time, count) in
           self.timeCount = count
        }
        self.wholeMode(out: sin)
    
    }
    
    func wholeMode(out:String) {
        
        NetEngine.reponse_wxQrLogin(out: out, success: { (mode) in
            RtcEngine.saveQRLoginData(mode: mode)
            UserInfoManager.shared.isLogin = true
            NotificationCenter.default.post(name: MTLoginStateNotification, object: nil)
            self.view.window?.close()
        }) {
            print("self.timeCount==\(self.timeCount)")
            if self.timeCount == 0 {
                self.qrInvalid.isHidden = false
            }else {
                self.wholeMode(out: out)
            }
        }
    }
    
    
    func setupUI()  {
        self.view.addSubview(sTitle)
        sTitle.snp.makeConstraints { (make) in
            make.width.equalTo(200)
            make.height.equalTo(32)
            make.centerX.equalToSuperview()
            make.top.equalTo(100)
        }
        
        self.view.addSubview(qrImageV)
        qrImageV.snp.makeConstraints { (make) in
            make.width.height.equalTo(kqrx)
            make.centerX.equalToSuperview()
            make.top.equalTo(sTitle.snp.bottom).offset(20)
        }
        
        self.view.addSubview(backLoginBtn)
        backLoginBtn.snp.makeConstraints { (make) in
            make.width.equalTo(200)
            make.height.equalTo(20)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-40)
        }
        
        self.view.addSubview(qrInvalid)
        qrInvalid.snp.makeConstraints { (make) in
            make.edges.equalTo(qrImageV)
        }
        
        qrInvalid.addSubview(qrInvalidTitle)
        qrInvalidTitle.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(20)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-20)
        }
        
        qrInvalid.addSubview(qrInvalidBtn)
        qrInvalidBtn.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(20)
        }
    }
    
    lazy var qrInvalid: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(0).withAlphaComponent(0.8).cgColor
        view.isHidden = false
        return view
    }()
    
    lazy var qrInvalidTitle: NSTextField = {
        let lab = NSTextField.label(title: "二维码已失效".localized(), textColor: color_gray(255), font: NSFont.boldSystemFont(ofSize: 16))
        lab.alignment = .center
        return lab
    }()
    
    lazy var qrInvalidBtn: ZHButton = {
        let btn = ZHButton()
        btn.wantsLayer = true
        btn.title = "点击刷新".localized()
        btn.font = NSFont.boldSystemFont(ofSize: 18)
        btn.zh_color = color_gray(255)
        btn.hasBorder = true
        btn.zh_cornerRadius = 15
        btn.zh_backgroundColor = NSColor.red
        btn.target = self
        btn.action = #selector(qrInvalidBtnAction(senber:))
        return btn
    }()
    
  
    
    lazy var qrImageV: NSImageView = {
        let imageV = NSImageView.init(frame: CGRect.zero)
        imageV.image =  QRManager.createQRImage(message: mt_url_pay, size: NSSize.init(width: kqrx, height: kqrx), backgroundColor: .white, foregroundColor: .black, fillImage: nil)
        return imageV
    }()
    
    lazy var sTitle:NSTextField  = {
        let lab = NSTextField.label(title: "扫码登录".localized(), textColor: color_gray(0), font: NSFont.systemFont(ofSize: 28))
        lab.alignment = .center
        return lab
    }()
    
    lazy var backLoginBtn: ZHButton = {
        let btn = ZHButton()
        btn.title = "返回其他登录".localized()
        btn.zh_color = color_gray(120)
        btn.target = self
        btn.action = #selector(backLoginAction(senber:))
        return btn
    }()
    
    @objc func backLoginAction(senber:ZHButton)  {
        
        guard let loginVc = self.view.superview?.jk_viewController() as? LoginViewController else {
           return
        }
        loginVc.switchTo(vc: loginVc.children[0])
    }
    
    @objc func qrInvalidBtnAction(senber:ZHButton) {
        self.sinle = nil
        self.reCheckLogin()
    }
}


extension LoginWechatViewController {
    @discardableResult
    func dispatchTimer(timeInterval: Double, repeatCount:Int, handler:@escaping (DispatchSourceTimer?, Int)->()) -> DispatchSourceTimer?{
        
        if repeatCount <= 0 {
            return nil
        }
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        
        var count = repeatCount
        timer.schedule(wallDeadline: .now(), repeating: timeInterval)
        timer.setEventHandler(handler: {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
            
        })
        timer.resume()
        return timer
    }
    
}


public extension Int {
    /*这是一个内置函数
     lower : 内置为 0，可根据自己要获取的随机数进行修改。
     upper : 内置为 UInt32.max 的最大值，这里防止转化越界，造成的崩溃。
     返回的结果： [lower,upper) 之间的半开半闭区间的数。
     */
    static func randomIntNumber(lower: Int = 0,upper: Int = Int(UInt32.max)) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower)))
    }
    /**
     生成某个区间的随机数
     */
    static func randomIntNumber(range: Range<Int>) -> Int {
        return randomIntNumber(lower: range.lowerBound, upper: range.upperBound)
    }
}
